package com.system.userserver.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.system.commonutils.bean.ApiResult;
import com.system.commonutils.bean.Token;
import com.system.commonutils.pojo.Role;
import com.system.commonutils.utils.RedisUtil;
import com.system.userserver.bean.UserInfo;
import com.system.userserver.service.CommonService;
import com.system.userserver.service.OauthService;
import com.system.userserver.service.UserOauthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class OauthServiceImp implements UserOauthService {

    @Resource
    private OauthService oauthService;


    @Autowired
    RedisUtil redisUtil;

    @Override
    public ApiResult adminlogin(String username, String password) {
        String json = oauthService.login(username, password);
        ApiResult login = JSONObject.parseObject(json, ApiResult.class);
        if(login.getCode()==200){
            Token token = JSONObject.parseObject(JSONObject.toJSONString(login.getData()), Token.class);
            String access_token = token.getAccess_token();
            UserInfo userBean = redisUtil.get(access_token, UserInfo.class);
            Integer user_statue = userBean.getUser_statue();
            if(user_statue == 0){
                System.out.println(userBean);
                return ApiResult.failure("登录失败,账号被禁用");
            }
            List<Role> roles = userBean.getRoles();
            for (Role role : roles) {
                Integer level = role.getLevel();
                System.out.println("角色"+role);
                if(level<=4){
                    return ApiResult.successWithData(token);
                }
            }
            System.out.println(redisUtil.get(access_token));
        }else {
            return ApiResult.failure("登录失败,获取授权失败");
        }
         return ApiResult.failure("登录失败,权限不足");
    }

    @Override
    public ApiResult userLogin(String username, String password) {
        String json = oauthService.login( username,  password);
        ApiResult login = JSONObject.parseObject(json, ApiResult.class);

        if(login.getCode()==200){
            Token token = JSONObject.parseObject(JSONObject.toJSONString(login.getData()), Token.class);
            String access_token = token.getAccess_token();
            UserInfo userBean = redisUtil.get(access_token, UserInfo.class);
            List<Role> roles = userBean.getRoles();
            for (Role role : roles) {
                Integer level = role.getLevel();
                if(level>4){
                    return ApiResult.successWithData(token);
                }
            }
        }

        return ApiResult.failure("登录失败");
    }
}
